package com.fudong.floatwindows;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private boolean hasBind = false;
    FloatWinfowServices.MyBinder binder;
    private Button btnTest;
    private EditText etContent;
    private Button btnAdd;
    ServiceConnection mVideoServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 获取服务的操作对象
            binder = (FloatWinfowServices.MyBinder) service;
            binder.getService().setOnServiceListener(new FloatWinfowServices.OnServiceListener() {
                @Override
                public void onClosed() {
                    unbindService(mVideoServiceConnection);
                    hasBind = false;
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView(){
        btnTest = findViewById(R.id.btn_test);
        etContent = findViewById(R.id.et_content);
        btnAdd = findViewById(R.id.btn_add);
        initListener();

    }



    private void initListener(){
        btnTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(hasBind){
                    return;
                }
                Intent intent = new Intent(MainActivity.this, FloatWinfowServices.class);
                hasBind = bindService(intent, mVideoServiceConnection, Context.BIND_AUTO_CREATE);
            }
        });

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!hasBind){
                    Toast.makeText(MainActivity.this,"请先添加浮窗",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(TextUtils.isEmpty(etContent.getText().toString().trim())){
                    Toast.makeText(MainActivity.this,"请输入内容",Toast.LENGTH_SHORT).show();
                    return;
                }
                binder.setText(etContent.getText().toString().trim(),60, Color.parseColor("#465734"));
            }
        });

    }
}